<style>
	@import "/static/css/common.css";
	@import "/static/css/user-index.css";
</style>
<template>
	<view class="back">
		<view v-if="!login">
			<view class="container" @click="toLogin">
				<view class="user-info">
					<image class="avatar" :src="avatar" mode="aspectFill"></image>
					<view class="info">
						<view class="info-line">
							<text class="nickname">未登录</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view v-else>
			<view class="container">
				<view class="user-info">
					<image class="avatar" :src="avatar" mode="aspectFill"></image>
					<view class="info">
						<view class="info-line">
							<text class="nickname">{{nickname}}</text>
						</view>
						<view class="info-line">
							<text class="username">账号：{{username}}</text>
						</view>
					</view>
					<view class="edit-btn" @click="showEditModal">
						<img src="/static/img/edit.jpg" alt="">
					</view>
				</view>
			</view>
			<!-- <view class="feature-list">
				<view class="feature-item" @click="goSettings">
					<image class="menu-icon" src="" mode="aspectFill"></image>
					<text class="feature-item-text">设置</text>
				</view>
			</view> -->
			<view class="logout" @click="logout">
				<image class="feature-icon" src="/static/img/exit.jpg" mode="aspectFill"></image>
				<text class="feature-item-text">退出登录</text>
			</view>
			<!-- 弹窗组件 -->
			<view v-if="isEditModalShown" class="edit-modal">
				<view class="mask" @click="onEditCancel"></view>
				<form class="edit-form" @submit="formSubmit">
					<view class="form-item back-img"
						:style="{ background: avatar ? 'url(' + avatar + ')' : 'url(/static/img/userAvatar.jpg)', 'background-repeat': 'no-repeat', 'background-size': 'cover' }">
						<image :src="avatarEdit" mode="aspectFill" class="avatar-edit elected-image"
							@click="chooseImage" :style="{ background: avatarEdit ? 'white' : 'none' }"></image>
					</view>
					<view class="form-item">
						<input class="input" type="number" name="id" v-model="userid" style="display: none;">
						<input class="input" type="text" placeholder="请输入昵称" name="nickname" v-model="nicknameEdit" />
					</view>
					<view class="button-area">
						<button class="confirm-btn" form-type="submit">确认</button>
						<button class="cancel-btn" @click="onEditCancel">取消</button>
					</view>
				</form>
			</view>
		</view>
		<Footer></Footer>
		<view v-if="tip" class="tip-layer">
			<view class="tip">{{tipContent}}</view>
		</view>
	</view>
</template>

<script>
	import Footer from '@/pages/footer/index.vue';
	import {
		showTips
	} from '@/static/js/common.js';

	export default {
		components: {
			Footer,
		},
		data() {
			return {
				httpUrl: "https://www.fengjian123.com/service9501/",
				imgUrl: "https://www.fengjian123.com/",
				// httpUrl: "http://192.168.200.128:9501/",
				// imgUrl: "http://192.168.200.128:8080/",
				isEditModalShown: false,
				userid: '',
				nickname: '',
				username: '',
				avatar: '',
				avatarEdit: '',
				nicknameEdit: '',
				tipContent: '',
				token: '',
				tip: 0,
				imgPath: '',
				login: 0
			};
		},
		onLoad() {
			this.getUser();
		},
		methods: {
			goSettings() {
				// 修改密码的方法
			},
			showEditModal() {
				this.isEditModalShown = true;
			},
			onEditCancel() {
				this.isEditModalShown = false;
			},
			getUser: function() {
				let _this = this;
				uni.getStorage({
					key: 'cookie',
					success: function(res) {
						if (res.data.id) {
							if (res.data.login) {
								const timestamp = new Date().getTime();
								_this.token = res.data.token;
								_this.userid = res.data.id;
								_this.username = res.data.username;
								_this.nickname = res.data.nickname;
								_this.nicknameEdit = res.data.nickname;
								_this.login = res.data.login;
								if (res.data.avatar) {
									_this.avatar = _this.imgUrl + res.data.avatar + '?t=' + timestamp;
								} else {
									_this.avatar = '/static/img/userAvatar.jpg';
								}
							} else {
								// setTimeout(() => {uni.reLaunch({url: '/pages/login/index',});}, 1000)  // 账号密码版
							}
						} else {
							_this.tips('网络不好，请检查网络..'); // _this.tips = '登录失效，正在跳转...'; // 账号密码版
							// setTimeout(() => {uni.reLaunch({url: '/pages/login/index',});}, 1000)  // 账号密码版
						}
					},
					fail: function() {
						_this.toLogin();
						// uni.reLaunch({url: '/pages/login/index',});  // 账号密码版
					}
				});
			},
			formSubmit: function(e) {
				let _this = this;
				let formdata = e.detail.value;
				uni.getStorage({
					key: 'cookie',
					success: function(res) {
						if (res.data.id) {
							_this.tips('修改中，请稍等...');
							let storage = res.data;
							let isEdit = 0;
							if (_this.avatarEdit) {
								++isEdit;
								uni.uploadFile({
									url: _this.httpUrl + 'user/uploadAvatar',
									filePath: _this.avatarEdit,
									name: 'file',
									header: {
										'Content-Type': 'application/json',
										'Authorization': 'Bearer ' + _this.token,
									},
									formData: {
										'userid': _this.userid
									},
									success: (res) => {
										let imgData = JSON.parse(res.data);
										if (imgData.err == 0) {
											const timestamp = new Date().getTime();
											_this.avatar = _this.imgUrl + imgData.imgPath +
												'?t=' +
												timestamp;
											_this.avatarEdit = '';
											storage.avatar = imgData.imgPath;
											uni.setStorageSync('cookie', storage);
											_this.tips(imgData.msg);
										} else if (imgData.err == 1) {
											_this.tips(imgData.msg);
										} else {
											uni.reLaunch({
												url: '/pages/index/index',
											});
											// 账号密码版
											// _this.tips(imgData.msg);
											// setTimeout(() => {uni.reLaunch({url: '/pages/login/index',});}, 1000)
										}
									},
									fail: function(res) {
										console.log(res);
									}
								});
							}
							if (_this.nicknameEdit !== _this.nickname) {
								++isEdit;
								uni.request({
									url: _this.httpUrl + 'user/userEdit',
									method: 'POST',
									header: {
										'Content-Type': 'application/json',
										'Authorization': 'Bearer ' + res.data.token,
									},
									data: {
										formdata: formdata
									},
									success: (res) => {
										console.log(res.data.msg);
										_this.tips(res.data.msg);
										if (res.data.err == 0) {
											_this.nickname = formdata.nickname;
											_this.nicknameEdit = formdata.nickname;
											storage.nickname = formdata.nickname;
											uni.setStorageSync('cookie', storage);
										} else if (res.data.err == 2) {
											uni.reLaunch({
												url: '/pages/index/index',
											});
											// 账号密码版
											// _this.tips(res.data.msg);
											// setTimeout(() => {uni.reLaunch({url: '/pages/login/index',});}, 1000)
										}
									},
									fail: (res) => {
										console.log("登录失败，请检查网络");
										_this.tips('登录失败，请检查网络');
									},
								});
							}
							_this.isEditModalShown = false;
						} else {
							_this.tips('登录失效，正在跳转...');
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/login/index',
								});
							}, 1000)
						}
					},
					fail: (res) => {
						console.log("获取缓存失败，需要重新登录");
					},
				});
			},
			chooseImage() {
				let _this = this;
				uni.chooseMedia({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: function(res) {
						if (res.tempFiles[0]['tempFilePath'] && res.tempFiles[0]['tempFilePath'].length > 0) {
							console.log(res.tempFiles[0]['tempFilePath']);
							_this.avatarEdit = res.tempFiles[0]['tempFilePath'];
						}
					}
				})
			},
			toLogin() {
				uni.navigateTo({
					url: '/pages/login/wx-index',
				})
			},
			logout() {
				let _this = this;
				uni.clearStorage();
				_this.tips('正在退出...');
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/index/index',
					});
				}, 1000)
				// setTimeout(() => {uni.reLaunch({url: '/pages/login/index',});}, 1000)  // 账号密码版
			},
			tips: function(content) {
				showTips(this, content);
			}
		},
	};
</script>